<?php
declare(strict_types=1);

namespace app\listener;

use app\model\{User, UserInviteRecord};
use think\facade\{Cache, Log};

class WorkChatEventListener
{
    /**
     * 处理群成员变动事件
     */
    public function onMemberChange($event)
    {
        try {
            $data = $event['message'];
            $merchantId = $data['merchant_id'];
            $chatId = $data['chat_id'];
            $joinUserIds = $data['join_user_list'] ?? [];
            
            // 获取群主信息
            $owner = User::where([
                'merchant_id' => $merchantId,
                'work_userid' => $data['owner']
            ])->find();
            
            if (!$owner) {
                Log::error('群主用户不存在', ['data' => $data]);
                return;
            }
            
            // 处理新加入成员
            foreach ($joinUserIds as $workUserId) {
                // 查找或创建用户
                $user = User::where([
                    'merchant_id' => $merchantId,
                    'work_userid' => $workUserId
                ])->find();
                
                if (!$user) {
                    // 创建用户
                    $user = User::create([
                        'merchant_id' => $merchantId,
                        'work_userid' => $workUserId,
                        'parent_id' => $owner->id,
                        'create_time' => time(),
                        'update_time' => time()
                    ]);
                    
                    // 记录邀请关系
                    UserInviteRecord::create([
                        'merchant_id' => $merchantId,
                        'inviter_id' => $owner->id,
                        'invitee_id' => $user->id,
                        'invite_type' => 3, // 企业微信群邀请
                        'create_time' => time()
                    ]);
                    
                    // 发送通知
                    event('UserInvited', [
                        'merchant_id' => $merchantId,
                        'inviter_id' => $owner->id,
                        'invitee_id' => $user->id
                    ]);
                }
            }
        } catch (\Exception $e) {
            Log::error('处理企业微信群成员变动事件异常: ' . $e->getMessage());
        }
    }
} 